package com.sita.linboard.receipt;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.sita.linboard.MainMessage.LastOrderBackBean;
import com.sita.linboard.R;
import com.sita.linboard.base.BaseActivity;
import com.sita.linboard.base.BaseApplication;
import com.sita.linboard.calllist.VehicleListActivity;
import com.sita.linboard.http.RestClient;
import com.sita.linboard.journey.OrderBackBean;
import com.sita.linboard.journey.OrderRequest;
import com.sita.linboard.utils.Constants;
import com.sita.linboard.utils.LogUtils;
import com.sita.linboard.utils.SpUtils;
import com.sita.linboard.utils.ToastUtils;
import com.squareup.picasso.Picasso;

import java.lang.ref.WeakReference;
import java.util.List;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by Jason on 2016/8/25.
 */
public class ReceiptActivity extends BaseActivity implements View.OnClickListener {
    private static int READYPAY;
    private static String tripID, Customer, startLocation, endLocation;
    private static double getMoney;
    private TextView stardinfo, endinfo, priceinfo, headtitle, waitState;
    private Button readyBt, callUser;
    private ImageView changeprice, waiting_pay_icon, customerAvatar;
    private EditText price_edit;
    private View viewLine;
    private RelativeLayout payMessage;
    private EMMessageListener msgListener;
    private String customerAvatarUrl;
    private MyHandler handler = new MyHandler(this);

    public static void ReceiptIntent(Context context, String userHXid, String CastmerName, String start, String end,
                                     double money) {
        Intent intent = new Intent(context, ReceiptActivity.class);
        tripID = userHXid;
        Customer = CastmerName;
        startLocation = start;
        endLocation = end;
        getMoney = money;
        context.startActivity(intent);
    }

    @Override
    protected void initData() {
        readyBt.setOnClickListener(this);
        stardinfo.setText(this.getString(R.string.start_location, startLocation));
        endinfo.setText(this.getString(R.string.start_location, endLocation));
        headtitle.setText("确认账单");
        //请求当前行程信息，获取乘客头像
        getCustomerAvatar(tripID);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        getPayState();
        READYPAY = 3;
        stardinfo = (TextView) findViewById(R.id.tour_price_startinfo);
        endinfo = (TextView) findViewById(R.id.tour_price_endinfo);
        readyBt = (Button) findViewById(R.id.tour_price_ready_bt);
        customerAvatar = (ImageView) findViewById(R.id.customer_avatar);
        priceinfo = (TextView) findViewById(R.id.tour_price_text);
        priceinfo.setText(String.valueOf(getMoney));
        /**
         * 修改金额， 预留
         */
        // changeprice = bindView(R.id.head_right_img);
        // changeprice.setVisibility(View.VISIBLE);

        headtitle = (TextView) findViewById(R.id.head_title);
        payMessage = (RelativeLayout) findViewById(R.id.pay_message);
        callUser = (Button) findViewById(R.id.call_to_user);
        callUser.setOnClickListener(this);

/**
 * 发布收款以后需要调整的状态
 */
        waiting_pay_icon = (ImageView) findViewById(R.id.money_icon);
        waitState = (TextView) findViewById(R.id.wait_pay);
        viewLine = findViewById(R.id.line_line);

    }

    @Override
    protected int getId() {
        return R.layout.activity_receipt;
    }

    //-----------**-----------------接收支付消息------------------**-----------//
    private void getPayState() {
        msgListener = new EMMessageListener() {
            @Override
            public void onMessageReceived(List<EMMessage> list) {

            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> list) {
                for (EMMessage msg : list) {
                    EMCmdMessageBody body = (EMCmdMessageBody) msg.getBody();
                    final String action = body.action();
                    if (action.equals("PAYTRIP")) {
                        Message message = new Message();
                        message.what = 1;
                        message.obj = msg.getStringAttribute("money", "");
                        handler.sendMessage(message);

                    }
                }
            }

            @Override
            public void onMessageReadAckReceived(List<EMMessage> list) {

            }

            @Override
            public void onMessageDeliveryAckReceived(List<EMMessage> list) {

            }

            @Override
            public void onMessageChanged(EMMessage emMessage, Object o) {

            }
        };
        //记住一定写到下面
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (Constants.isPress == 0) {
            Constants.isReady = false;
        } else if (Constants.isPress == 1) {
            Constants.isReady = true;
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.head_right_img:
                View view = LayoutInflater.from(this).inflate(R.layout.dialog_changeprice, null);
                price_edit = (EditText) view.findViewById(R.id.price_editTx);
                AlertDialog dialog = new AlertDialog.Builder(this).
                        setView(view).setTitle("编辑金额")
                        .setCancelable(false)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String price = price_edit.getText().toString();
                                if (price.length() != 0) {
                                    dialog.dismiss();
                                    priceinfo.setText(getString(R.string.priceinfo, Integer.valueOf(price)));
                                } else {
                                    ToastUtils.showLong("输入金额有误！请重新输出");
                                }
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).show();


                break;
            case R.id.tour_price_ready_bt:
                if (READYPAY == 3) { //发起收款
                    //TODO

                    OrderRequest request = new OrderRequest();
                    request.trip_id = SpUtils.getString("trip_id", null, BaseApplication.getContext());
                    RestClient.getRestService().pay(request, new Callback<OrderBackBean>() {
                        @Override
                        public void success(OrderBackBean orderBackBean, Response response) {
                        }

                        @Override
                        public void failure(RetrofitError error) {

                        }
                    });

                    readyBt.setText("继续接单");
                    headtitle.setText("订单详情");
                    waiting_pay_icon.setVisibility(View.VISIBLE);
                    waitState.setVisibility(View.VISIBLE);
                    viewLine.setVisibility(View.VISIBLE);
                    //payMessage
                    RelativeLayout.LayoutParams rp = (RelativeLayout.LayoutParams) payMessage.getLayoutParams();
                    rp.setMargins(0, 350, 0, 0);

                    payMessage.setLayoutParams(rp);


                    READYPAY = 4;
                } else {
                    VehicleListActivity.VehicleListIntent(this);
                    finish();
                    ReceiptActivity.this.onDestroy();
                }

                break;
            case R.id.call_to_user:
                BaseActivity.callToUser(this);
                break;

        }

    }

    //在屏蔽系统back键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return false;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        return false;
    }

    private void getCustomerAvatar(String tripId) {
        OrderRequest request = new OrderRequest();
        request.trip_id = tripId;
        RestClient.getRestService().getOneOrder(request, new Callback<LastOrderBackBean>() {
            @Override
            public void success(LastOrderBackBean lastOrderBackBean, Response response) {
                if (lastOrderBackBean.getErrorCode().equals("0")) {
                    customerAvatarUrl = lastOrderBackBean.getData().getCustomer().getAvatar();
                    Picasso.with(ReceiptActivity.this).load(customerAvatarUrl.isEmpty() ? null : customerAvatarUrl).fit().into(customerAvatar);
                }
            }

            @Override
            public void failure(RetrofitError error) {
                LogUtils.d("获取订单失败");
            }
        });
    }

    //----------------------------------------接收支付结果
    static class MyHandler extends Handler {
        WeakReference<ReceiptActivity> thisActivity;

        MyHandler(ReceiptActivity activity) {
            thisActivity = new WeakReference<ReceiptActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final ReceiptActivity receiptActivity = thisActivity.get();
            if (msg.what == 1) {
                receiptActivity.waiting_pay_icon.setImageResource(R.mipmap.pay_finish);
                receiptActivity.waitState.setText("支付完成");
            }
        }
    }
}
